import re
from typing import Dict, List

class ContentFormatter:
    """内容格式化工具"""
    
    def __init__(self):
        self.section_patterns = {
            'abstract': r'(?i)## Abstract\n(.*?)(?=\n##|\Z)',
            'introduction': r'(?i)## Introduction[^#]*(.*?)(?=\n##|\Z)',
            'main_content': r'(?i)## (?!Abstract|Introduction|References)(.*?)(?=\n##|\Z)',
            'references': r'(?i)## References\n(.*?)(?=\n##|\Z)'
        }

    def format_content(self, content: str) -> str:
        """格式化内容"""
        # 规范化标题格式
        content = self._format_headers(content)
        # 规范化段落间距
        content = self._format_paragraphs(content)
        # 规范化引用格式
        content = self._format_citations(content)
        # 规范化列表格式
        content = self._format_lists(content)
        # 规范化表格格式
        content = self._format_tables(content)
        # 规范化图表格式
        content = self._format_diagrams(content)
        return content

    def _format_headers(self, content: str) -> str:
        """格式化标题"""
        # 确保一级标题前有空行
        content = re.sub(r'(?<!\n\n)# ', r'\n\n# ', content)
        # 确保二级标题前有空行
        content = re.sub(r'(?<!\n\n)## ', r'\n\n## ', content)
        # 确保三级标题前有空行
        content = re.sub(r'(?<!\n\n)### ', r'\n\n### ', content)
        # 确保标题后有空行
        content = re.sub(r'(#+ .+)\n(?!\n)', r'\1\n\n', content)
        return content

    def _format_paragraphs(self, content: str) -> str:
        """格式化段落"""
        # 规范化段落间距
        content = re.sub(r'\n{3,}', '\n\n', content)
        # 确保段落之间有空行
        content = re.sub(r'([^\n])\n([^\n#\-\|])', r'\1\n\n\2', content)
        return content

    def _format_citations(self, content: str) -> str:
        """格式化引用"""
        # 修正引用标记位置
        content = re.sub(r'\.\s*<sup>', '<sup>', content)
        content = re.sub(r'</sup>\s*\.', '</sup>.', content)
        # 确保引用标记和文本之间没有空格
        content = re.sub(r'\s+<sup>', '<sup>', content)
        content = re.sub(r'</sup>\s+', '</sup>', content)
        return content

    def _format_lists(self, content: str) -> str:
        """格式化列表"""
        # 统一列表标记为短横线
        content = re.sub(r'(?m)^\*\s', '- ', content)
        # 确保列表项前后有空行
        content = re.sub(r'\n(?!\n)- ', '\n\n- ', content)
        content = re.sub(r'(- .+)\n(?!\n|\s*-)', r'\1\n\n', content)
        return content

    def _format_tables(self, content: str) -> str:
        """格式化表格"""
        # 确保表格前后有空行
        content = re.sub(r'\n(?!\n)\|', '\n\n|', content)
        content = re.sub(r'\|[^\n]*\n(?!\n|\s*\|)', r'\0\n', content)
        return content

    def _format_diagrams(self, content: str) -> str:
        """格式化图表"""
        # 确保mermaid图表前后有空行
        content = re.sub(r'\n(?!\n)```mermaid', '\n\n```mermaid', content)
        content = re.sub(r'```\n(?!\n)', '```\n\n', content)
        return content
